package com.mh.config;

import com.mh.dto.bo.UseCouponBo;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 * Date:2024/10-26
 * author:zmh
 * description:RabbitMQ配置类
 **/

@Configuration
public class RabbitMQConfig {

    // 声明创建一个预支付订单处理队列
    @Bean
    public Queue prePayQueue() {
        return new Queue("prePayOrder", true);
    }

    // 定义成功支付消息队列
    @Bean
    public Queue successPayQueue() {
        return new Queue("successPay", true);
    }

    // 处理优惠券使用，创建使用记录信息
    @Bean
    public Queue createUseCouponQueue() {
        return new Queue("useCoupon", true);
    }

    // 声明一个延迟队列的交换机
    @Bean
    public CustomExchange delayedExchange() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-delayed-type", "direct");
        return new CustomExchange("delayed.exchange", "x-delayed-message", true, false, args);
    }

    // 延迟队列
    @Bean
    public Queue delayedQueue() {
        return new Queue("delayed.queue", true);
    }

    // 绑定延迟交换机和队列
    @Bean
    public Binding binding() {
        return BindingBuilder.bind(delayedQueue()).to(delayedExchange()).with("delayed.queue").noargs();
    }


    // 配置消息转换器为 Jackson2JsonMessageConverter，实现复杂对象发送的支持
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        return factory;
    }
}
